package com.qiye.pointsserver.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qiye.pointsserver.common.PageUtil.PageParam;
import com.qiye.pointsserver.common.PageUtil.PageParams;
import com.qiye.pointsserver.common.PageUtil.PageResult;
import com.qiye.pointsserver.common.result.Result;
import com.qiye.pointsserver.model.dto.PointsLogDto;
import com.qiye.pointsserver.model.dto.PointsLosgDto;
import com.qiye.pointsserver.model.entity.*;
import com.qiye.pointsserver.model.vo.PointsLogVO;
import com.qiye.pointsserver.service.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Tag(name = "04.积分日志模块")
@RestController
@RequestMapping("/api/v1/pointsLog")
@RequiredArgsConstructor
@Slf4j
public class PointsLogController {

    @Resource
    private PointslogService pointslogService;

    @Resource
    private ProductService productService;

    @Resource
    private AutherService autherService;

    @Resource
    private UserinfoService userinfoService;

    @Resource
    private UserService userService;


    @Operation(summary = "添加积分日志")
    @PostMapping("/add")
    @Transactional
    public Result add(@RequestBody PointsLogDto pointsLogDto){
        Pointslog pointslog = new Pointslog();
        try {
            if (pointsLogDto.getType() == 0){
                LambdaQueryWrapper<Product> productLambdaQueryWrapper = new LambdaQueryWrapper<>();
                productLambdaQueryWrapper.eq(Product::getId,pointsLogDto.getId());
                Product product = productService.getBaseMapper().selectOne(productLambdaQueryWrapper);
                pointslog.setTime(product.getTime());
                pointslog.setUserinfoId(pointsLogDto.getUserinfoId());
                pointslog.setType(product.getName());
                pointslog.setDesc(product.getDesc());
                if (pointsLogDto.getIsDouble() == 1){
                    pointslog.setPoints(
                            product.getPoints()
                                    .multiply(BigDecimal.valueOf(2))
                                    .multiply(BigDecimal.valueOf(pointsLogDto.getCount()))
                    );


                    pointslog.setIsDouble(pointsLogDto.getIsDouble());
                }
                else {
                    pointslog.setPoints(product.getPoints()
                                        .multiply(BigDecimal.valueOf(pointsLogDto.getCount())));
                    pointslog.setIsDouble(pointsLogDto.getIsDouble());
                }
                pointslogService.save(pointslog);
            }
            else {
                LambdaQueryWrapper<Auther> autherLambdaQueryWrapper = new LambdaQueryWrapper<>();
                autherLambdaQueryWrapper.eq(Auther::getId,pointsLogDto.getId());
                Auther auther = autherService.getBaseMapper().selectOne(autherLambdaQueryWrapper);
                pointslog.setTime(auther.getTime());
                pointslog.setUserinfoId(pointsLogDto.getUserinfoId());
                pointslog.setType(auther.getType());
                pointslog.setDesc(auther.getDescribe());
                if (pointsLogDto.getIsDouble() == 1){
                    pointslog.setPoints(auther.getPoints().multiply(new BigDecimal("2")));
                    pointslog.setIsDouble(pointsLogDto.getIsDouble());
                }
                else {
                    pointslog.setPoints(auther.getPoints());
                    pointslog.setIsDouble(pointsLogDto.getIsDouble());
                }
                pointslogService.save(pointslog);
            }
            return Result.success("添加积分日志成功");
        }catch (Exception e){
            return Result.failed("添加积分日志失败");
        }
    }



    @Operation(summary = "关键词分页查询")
    @PostMapping("/search")
    public Result searcPointsLog(@RequestBody PageParams pageParam) {
        PageResult<Pointslog> pointsloogList = pointslogService.searchPointslog(pageParam);
        return Result.success(pointsloogList);
    }

    @Operation(summary = "根据姓名查询用户总积分及姓名")
    @PostMapping("/totalPoints")
    public Result totalPoints(@RequestParam(value = "name", required = false) String name) {
        // 1. 查询 role=2 的用户ID列表
        LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(User::getRole, 2);
        List<User> userList = userService.list(userWrapper);
        List<Integer> userIds = userList.stream()
                .map(User::getId)
                .collect(Collectors.toList());

        // 如果没有符合条件的用户，直接返回空结果
        if (userIds.isEmpty()) {
            return Result.success(Collections.emptyList());
        }

        // 2. 查询 userinfo 表，根据 userIds 和 name 模糊查询
        LambdaQueryWrapper<Userinfo> userinfoWrapper = new LambdaQueryWrapper<>();
        userinfoWrapper.in(Userinfo::getUserId, userIds);
        if (name != null && !name.trim().isEmpty()) {
            userinfoWrapper.like(Userinfo::getName, name);
        }
        List<Userinfo> userinfoList = userinfoService.list(userinfoWrapper);

        List<PointsLogVO> resultList = new ArrayList<>();

        // 3. 统计积分
        for (Userinfo userinfo : userinfoList) {
            Integer userId = userinfo.getUserId();

            LambdaQueryWrapper<Pointslog> pointslogWrapper = new LambdaQueryWrapper<>();
            pointslogWrapper.eq(Pointslog::getUserinfoId, userId)
                    .and(w -> w.gt(Pointslog::getTime, 0).or().isNull(Pointslog::getTime));
            List<Pointslog> pointslogs = pointslogService.list(pointslogWrapper);

            BigDecimal totalPoints = BigDecimal.ZERO;
            for (Pointslog log : pointslogs) {
                totalPoints = totalPoints.add(log.getPoints());
            }

            PointsLogVO vo = new PointsLogVO();
            vo.setUserinfoId(userinfo.getUserId());
            vo.setName(userinfo.getName());
            vo.setPoints(totalPoints);

            resultList.add(vo);
        }

        return Result.success(resultList);
    }




    @Operation(summary = "根据 userinfoId 查询积分总和（time > 0 或 time 为空）")
    @GetMapping("/totalPointsByUserinfoId/{userinfoId}")
    public Result totalPointsByUserinfoId(@PathVariable Integer userinfoId) {

        LambdaQueryWrapper<Pointslog> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Pointslog::getUserinfoId, userinfoId)
                .and(w -> w.gt(Pointslog::getTime, 0)
                        .or()
                        .isNull(Pointslog::getTime));   // time > 0 或 time 为空

        List<Pointslog> pointslogs = pointslogService.list(wrapper);

        BigDecimal totalPoints = pointslogs.stream()
                .map(Pointslog::getPoints)
                .reduce(BigDecimal.ZERO, BigDecimal::add);


        return Result.success(totalPoints);
    }



    @Operation(summary = "积分兑换")
    @PostMapping("/exchange")
    public Result exchangePoints(@RequestBody PointsLosgDto pointsLogDto) {
        Pointslog pointslog = new Pointslog();
        pointslog.setUserinfoId(pointsLogDto.getUserinfoId());
        pointslog.setPoints(pointsLogDto.getPoints());
        pointslog.setType(pointsLogDto.getType());
        pointslogService.save(pointslog);
        return Result.success("积分兑换成功");
    }


}
